package com.edu.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import com.edu.entity.Users;
import com.edu.service.impl.UsersServiceImpl;
import com.edu.util.MD5;
import com.edu.util.VerifyCode;
import com.google.gson.Gson;

/**
 * Servlet implementation class UsersController
 */
@WebServlet("/UsersController")
@MultipartConfig
public class UsersController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UsersServiceImpl service=new UsersServiceImpl();
	VerifyCode verifyCode=new VerifyCode();
	
	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public UsersController() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		//获取参数  参数名op的值如果是等于query才做查询
		String op=request.getParameter("op");
		//提升:加入session的判断:从session中获取用户登录的信息,如果有,才能执行查询,添加等等的操作
		HttpSession session=request.getSession();
		Object obj=session.getAttribute("frontUser");
		if(obj!=null) {
			if ("frontExit".equals(op)) {
				//移除frontUser
				request.getSession().removeAttribute("frontUser");
				response.sendRedirect("front/index.jsp");
			}
		}else if ("Login".equals(op)) {
			usersLogin(op,request,response);
		}else if("register".equals(op)) {
			userRegiter(request,response);
		}else if("checkName".equals(op)) {
			checkName(request,response);
		}else if ("getimg".equals(op)) {
			VerifyCode.output(verifyCode.getImage(), response.getOutputStream());
		}else if ("getImgText".equals(op)) {
			String text=verifyCode.getText().toLowerCase();
			HttpSession session1 = request.getSession();  //保存到session
			session1.setAttribute("verificationCode", text);
			response.getWriter().print(text);
		}else if ("addScore".equals(op)) {
			addScore(request,response);
		}
	}

	private void addScore(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		//获去userId
		String userId = request.getParameter("userId");
		Integer id = Integer.getInteger(userId);
		System.out.println(id);
		boolean flag = service.addUserScore(id);
		Gson gson=new Gson();
		String json = gson.toJson(flag);
		response.getWriter().print(json);
		response.getWriter().close();
		
	}

	private void checkName(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// TODO Auto-generated method stub
		//获取
		String unama=request.getParameter("uname");
		//调用判断用户名方法
		boolean flag=service.getUserAccount(unama);
		if (flag) {
			response.getWriter().print("用户名已存在");
		}else {
			response.getWriter().print("用户名可用");
		}
	}

	private void userRegiter(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		response.setContentType("text/html;charset=utf-8");
		//执行注册功能
		String userAccount=request.getParameter("userAccount");
		boolean flag=service.getUserAccount(userAccount);
		if (!flag) {
			String userPwd=request.getParameter("userPwd");
			String userRealName=request.getParameter("userRealName");
			long userPhone=Long.parseLong(request.getParameter("userPhone"));
			String userMail=request.getParameter("userMail");
			//接收文件组件
			Part part=request.getPart("userImg");
			//System.out.println(part.getSize());
			//判断是否上传文件
			if(part.getSize()==0) {
				//调用业务层添加用户
				service.userregister(new Users(userAccount, userPwd, null, userRealName, userPhone, userMail));
				//注册成功跳转首页
				response.getWriter().print("<script>alert('注册成功');location.href='front/index.jsp'</script>");
			}else {
				//创建目录，文件储存位置
				File file=new File("D:\\uploadFile");
				if(!file.exists()) {
					//创建目录
					file.mkdir();
				}
				//3.获取文件真实名，通过请求头获取
				String header = part.getHeader("content-disposition");
				String realName=header.substring(header.indexOf("filename=")+10,header.length()-1);
				System.out.println("文件真实名"+realName);
				//为了避免文件名重复，在文件名前面加uuid唯一标识符
				UUID uuid=UUID.randomUUID();
				String newFilerName=uuid+realName;
				//4.文件全路径
				String filePath="D:\\uploadFile\\"+newFilerName;
				//5.真正将文件写入本地
				part.write(filePath);
				//调用注册方法
				boolean flag1=service.userregister(new Users(userAccount, userPwd, newFilerName, userRealName, userPhone, userMail));
				if (flag1) {
					//注册成功
					response.getWriter().print("<script>alert('注册成功');location.href='front/index.jsp'</script>");
				}else {
					response.getWriter().print("<script>alert('注册失败');location.href='front/sign-up.jsp'</script>");
				}
			}
		}else {
			response.getWriter().print("<script>location.href='front/sign-up.jsp'</script>");
		}
	}

	//用户登录
	private void usersLogin(String op,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取登录信息
		String username=request.getParameter("userAccount");
		String userpwd=request.getParameter("userPwd");
		String password=MD5.getMD5(userpwd);
		//调用函数
		Users users=service.userlogin(username, password);
		if(users!=null) {
			//用户名密码正确
			if(users.getUserStatus()==1) {
				//System.out.println("002");
				//提升->加入访问控制:登录成功后要将用户登录信息存储在session中
				HttpSession session1=request.getSession();
				session1.setAttribute("frontUser",users);
				//request.getRequestDispatcher("front/index.jsp").forward(request, response);
				
				Gson gson=new Gson();
				String json=gson.toJson(users);
				response.getWriter().print(json);
				response.getWriter().close();
			}
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
